﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;

namespace OAuth2Authorizer.Serialization
{
    internal class FormEncodedSerializer<T> : ISerializer<T>
    {
        private NameValueCollectionSerializer _serializer = new NameValueCollectionSerializer();

        // restrictions: applies only to simple objects with name=value pairs
        public T ReadObject(Stream stream)
        {
            var propertyBag = _serializer.ReadObject(stream);
            T obj = (T)Activator.CreateInstance(typeof(T));
            if (propertyBag != null && propertyBag.Count > 0)
            {
                // Get all the data member attributes
                var attributeMap = new Dictionary<string, PropertyInfo>();
                foreach (var pi in obj.GetType().GetProperties())
                {
                    var attr = (DataMemberAttribute)pi.GetCustomAttributes(typeof(DataMemberAttribute), false).SingleOrDefault();
                    attributeMap.Add(attr.Name, pi);
                }

                foreach (var property in propertyBag.AllKeys)
                {
                    // this should match the name value in the DataMember attribute
                    if (attributeMap.ContainsKey(property))
                        attributeMap[property].SetValue(obj, propertyBag[property], null);
                }
            }
            return obj;
        }

        public void WriteObject(Stream stream, T obj)
        {
            
        }
    }
}
